package cn.itsource.config.aop;

import cn.itsource.config.anno.MyLog;
import cn.itsource.domain.SysOperLog;
import cn.itsource.service.BlogSysOperLogService;
import cn.itsource.util.UserTools;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

/**
 * 日志切面管理类
 */
@Aspect
@Component
public class LogManager {
    @Autowired
   private BlogSysOperLogService service;
    @Pointcut("execution(* cn.itsource.service.Blog*Service.*(..))")
//    日志切入点
    public void logPointcut(){
    }
//    环绕切入
    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
//        打印参数
        String args = Arrays.toString(pjp.getArgs());
        System.out.println(args);

//        获取pjp签名
        Signature signature = pjp.getSignature();
//        获取方法名
        String methodName = signature.getName();
        System.out.println(methodName);
        MethodSignature methodSignature = (MethodSignature)signature;
//        获取方法
        Method method = methodSignature.getMethod();
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            SysOperLog sysOperLog = new SysOperLog();
            sysOperLog.setId(null);
            sysOperLog.setRealName(UserTools.getCurrentUserRealName());
            sysOperLog.setCreateTime(new Date());
            boolean important = myLog.isImportant();
            switch (methodName){
                case "delete" :
                    methodName = "删除";
                    break;
                    case "save" :
                    methodName = "新增";
                    break;
                    case "update" :
                    methodName = "修改";
                    break;
                    case "findOne" :
                    methodName = "查看单条数据";
                    break;
            }
            if (important) {
                sysOperLog.setContent("[重要日志提醒]--关于数据源:==["+myLog.value()+"==]{数据参数:{---"+args+"---},==>被"+methodName);
            } else {
                sysOperLog.setContent("操作人对数据源["+myLog.value()+"]进行了"+"--["+methodName+"]--的操作");
            }
            service.save(sysOperLog);
        }
        return pjp.proceed();
    }
}
